﻿using System;
using AppCommon;
using Controller;
using Model;

public partial class ACPanel_AdminPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["VYCTravel"] == null)
            {                
                Response.Redirect("~/ACPanel/");                
            }
            else
            {
                // var info = (ModelVYC17) Session[Constants.SESSION_ADMIN];
                var userCookie = Request.Cookies["VYCTravel"];
                var username = Common.Decrypt(userCookie["Title"]);
                var pwh = Common.Decrypt(userCookie["Desc"]);
                var name = Common.Decrypt(userCookie["Content"]);
                CheckCookie(username, pwh, name);
            }
        }
    }

    public void CheckCookie(string u, string pwh, string name)
    {
        var user = new ModelVYC17();
        var passHash = pwh;
        user.UserName = u;
        user.PasswordHash = passHash;

        var controller = new VYC17Controller();
        var listUser = controller.CheckLogin(user);

        if (listUser.Count <= 0)
        {
            Response.Redirect("~/ACPanel/");
        }
        else
        {
            litUser.Text = name;
        }
    }

    protected void LinkButton1_OnClick(object sender, EventArgs e)
    {
        // Thuc hien logout
        // 0. Luu log
        var model = Request.Cookies["VYCTravel"];
        if (model != null)
        {
            // var model = (ModelVYC17) Session[Constants.SESSION_ADMIN];
            var logInfo = new ModelVYC20();
            var logConroller = new VYC20Controller();

            logInfo.Ten = "Đăng xuất";
            logInfo.ThongTin = "Đăng xuất khỏi trang quản trị thành công vào lúc " + DateTime.Now.ToLongDateString();
            logInfo.TrangThai = 1;
            logInfo.UserName = Common.Decrypt(model["Title"]);

            logConroller.AddData(logInfo);
            // 1. Remove session
            // Session.Remove(Constants.SESSION_ADMIN);
            // Remove cookie
            // Response.Cookies.Remove("VYCTravel");
            model.Expires = DateTime.Now.AddDays(-1D);
            Response.Cookies.Add(model);
            // 2. Redirect den trang login
            Response.Redirect("~/ACPanel/");
        }
        else
        {
            Response.Redirect("~/ACPanel/Error.aspx");
        }
    }
}
